<template>
  <view class="container">
    <view class="wechatapp">
      <view class="header">
        <!-- <open-data class="avatar" type="userAvatarUrl"></open-data> -->
        <image class="image" src="/static/user/logo.png"></image>
      </view>
    </view>
    <view class="auth-title">申请获取以下权限</view>
    <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
    <view class="login-btn">
      <!-- 获取微信用户信息 -->
      <!--        <button-->
      <!--        class="button btn-normal"-->
      <!--        open-type="getPhoneNumber"-->
      <!--        @getphonenumber="getPhoneNumber"-->
      <!--      >-->
      <!--        微信用户一键登录-->
      <!--      </button>-->
      <view class="button btn-normal">
        <!--      @tap="getUserProfile"   -->
        <button
          class="button btn-normal"
          style="width: 100%"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          授权登录
        </button>
      </view>
    </view>
    <view class="no-login-btn">
      <button class="button btn-normal" @tap="handleCancel">暂不登录</button>
    </view>
    <view class="checkBox_wrapper">
      <!--      <u-checkbox-group @change="checkboxGroupChange">-->
      <!--        <u-checkbox-->
      <!--          shape="circle"-->
      <!--          @change="checkboxChange"-->
      <!--          v-model="item.checked"-->
      <!--          v-for="(item, index) in list"-->
      <!--          :key="index"-->
      <!--          name="false"-->
      <!--        ></u-checkbox>-->
      <!--      </u-checkbox-group>-->
      <!--      <view>若手机号未注册将进入注册流程，注册即视为同意。</view>-->
    </view>
  </view>
</template>

<script>
import { getLogin, getPhone, wxLoginApi } from "@/api/login/login";

const app = getApp();
export default {
  data() {
    return {
      value: false,
      // 商城基本信息
      storeInfo: undefined,
      // 微信小程序登录凭证 (code)
      // 提交到后端，用于换取openid
      code: "",
      list: [
        {
          name: "注册",
          checked: false,
          disabled: false,
        },
      ],
    };
  },

  created() {},
  beforeDestroy() {
    console.log("返回了");
    if (!uni.getStorageSync("token")) {
      uni.removeStorageSync("token");
      uni.removeStorageSync("userInfoServer");
      uni.removeStorageSync("userId");
      uni.removeStorageSync("openId");
      uni.removeStorageSync("MyUserInfo");
      uni.removeStorageSync("phoneNumber");
    }
  },
  onLoad() {},
  methods: {
    // 选中某个复选框时，由checkbox时触发
    checkboxChange(e) {
      console.log(e, "123");
      this.value = e.value;
      console.log(this.value, "value");
    },
    // 选中任一checkbox时，由checkbox-group触发
    checkboxGroupChange(e) {
      console.log(e, "345");
    },

    //用户登录凭证code
    getCode() {
      const than = this;
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            console.log(res.code, "res code");
            resolve(res.code);
          },
          fail: reject,
        });
      });
    },

    async getPhoneNumber(e) {
      console.log(e, "eee");
      console.log(e.detail.code, "e 手机code");
      const code = await this.getCode();
      console.log(code, "登录用得code");
      const app = this;
      if (e.detail.code) {
        const data = {
          phoneCode: e.detail.code,
          wxOpenIdCode: code,
          parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
        };
        //登录接口
        const logoData = await wxLoginApi(data);
        console.log(logoData, "提交到后端登录接口");
        if (logoData.code === 0) {
          uni.showToast({
            title: "登录成功",
            icon: "success",
            duration: 2000,
          });
          // 获取到的当前数据存入缓存
          const { wxToken, openId, userInfo } = logoData.data;
          uni.setStorageSync("token", wxToken);
          uni.setStorageSync("openId", userInfo.wxOpenid);
          uni.setStorageSync("userInfoServer", userInfo);
          uni.setStorageSync("phoneNumber", userInfo.phone);
          uni.setStorageSync("userId", userInfo.userId);
          setTimeout(() => {
            app.handleCancel();
          }, 1500);
        } else {
          uni.showToast({
            title: "登录失败",
            icon: "success",
            duration: 2000,
          });
          setTimeout(() => {
            app.handleCancel();
          }, 1500);
        }
      }
    },

    // getUserProfile() {
    //   uni.showLoading({
    //     title: "加载中...",
    //   });
    //   //获取用户信息 包含appid
    //   // const appid = uni.getAccountInfoSync();
    //   // console.log(appid, "appid");
    //   const app = this;
    //   console.log("登录授权开始");
    //   wx.canIUse("getUserProfile") &&
    //     wx.getUserProfile({
    //       lang: "zh_CN",
    //       desc: "获取用户相关信息",
    //       async success(res) {
    //         console.log("用户同意了授权");
    //         console.log("用户信息:", res);
    //         // const { encryptedData, iv } = res;
    //         const {
    //           gender,
    //           avatarUrl,
    //           city,
    //           country,
    //           language,
    //           nickName,
    //           province,
    //         } = res.userInfo;
    //         uni.setStorageSync("MyUserInfo", res.userInfo);
    //         // const code = await app.getCode();
    //         uni.login({
    //           provider: "weixin",
    //           success: async (codeData) => {
    //             // app.data.encryptedData = encryptedData;
    //             // app.data.iv = iv;
    //             const data = {
    //               code: codeData.code,
    //               // wxEncryptInfo: {
    //               //   encryptedData: app.trimAll(encryptedData),
    //               //   iv,
    //               // },
    //               memberInfo: {
    //                 avatarUrl: avatarUrl || "",
    //                 city: city || "",
    //                 country: country || "",
    //                 gender: gender || "",
    //                 language: language || "",
    //                 nickName: nickName || "",
    //                 province: province || "",
    //               },
    //               parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
    //             };
    //             //登录接口
    //             const logoData = await getLogin(data);
    //             console.log(logoData, "提交到后端登录接口");
    //             if (logoData.code === 0) {
    //               uni.hideLoading();
    //               uni.showToast({
    //                 title: "登录成功",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               // 获取到的当前数据存入缓存
    //               const { wxToken, openId, userInfo } = logoData.data;
    //               uni.setStorageSync("token", wxToken);
    //               uni.setStorageSync("openId", userInfo.wxOpenid);
    //               uni.setStorageSync("userInfoServer", userInfo);
    //               uni.setStorageSync("phoneNumber", userInfo.phone);
    //               uni.setStorageSync("userId", userInfo.userId);
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //               return true;
    //             } else {
    //               uni.showToast({
    //                 title: "登录失败",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //             }
    //           },
    //           fail: (err) => {
    //             console.log(err, "登录错误");
    //           },
    //         });
    //       },
    //       fail() {
    //         console.log("用户拒绝了授权");
    //       },
    //     });
    // },

    // async getPhoneNumber(e) {
    //   console.log(e,'eee')
    //   console.log(e.detail.code, "e 手机code");
    //   const code=await this.getCode()
    //   console.log(code,'登录用得code')
    //   //这里获取code
    //   return;
    //   if (e.detail.code) {
    //     //获取手机号
    //     const getPhoneData = await getPhone(e.detail.code);
    //     if (getPhoneData.code === 0) {
    //       const { phoneNumber } = getPhoneData.data.phone_info;
    //       uni.setStorageSync("phoneNumber", phoneNumber);
    //       uni.showToast({
    //         title: "授权成功",
    //         icon: "success",
    //         duration: 2000,
    //       });
    //       setTimeout(() => {
    //         this.handleCancel();
    //       }, 1500);
    //     } else {
    //       uni.showToast({
    //         title: "授权失败",
    //         icon: "error",
    //         duration: 2000,
    //       });
    //     }
    //   }
    // },

    /**
     * 暂不登录
     */
    handleCancel() {
      // 跳转回原页面
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 登录成功-跳转回原页面
     */
    // onNavigateBack(delta = 1) {
    //   const pages = getCurrentPages();
    //   if (pages.length > 1) {
    //     uni.navigateBack({
    //       delta: Number(delta || 1),
    //     });
    //   } else {
    //     uni.navigateBack({
    //       delta: 1,
    //     });
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
u-checkbox-group::v-deep {
  .u-checkbox__label {
    margin-right: rpx(0);
  }
}

.checkBox_wrapper {
  font-size: rpx(12);
  display: flex;
}

.container {
  padding: 0 60rpx;
  font-size: 32rpx;
  background: #fff;
  min-height: 100vh;
}

.wechatapp {
  padding: 80rpx 0 48rpx;
  //border-bottom: 1rpx solid #e3e3e3;
  margin-bottom: 72rpx;
  text-align: center;

  .header {
    width: 190rpx;
    height: 190rpx;
    border: 4rpx solid #fff;
    margin: 0 auto 0;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

    .image {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}

.auth-title {
  color: #585858;
  font-size: 34rpx;
  margin-bottom: 40rpx;
}

.auth-subtitle {
  color: #888;
  margin-bottom: 88rpx;
  font-size: 28rpx;
}

.login-btn {
  //padding: 0 20rpx;
  margin-bottom: rpx(13);

  .button {
    height: 88rpx;
    //background: #04be01;
    color: #fff;
    background: #fc3100;
    font-size: 30rpx;
    border-radius: rpx(5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.no-login-btn {
  margin-top: 20rpx;
  //padding: 0 20rpx;

  .button {
    height: 88rpx;
    background: #dfdfdf;
    color: #fff;
    font-size: 30rpx;
    border-radius: rpx(5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
